package com.lxq.smartsign.client.ui.gallery;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.lxq.smartsign.client.databinding.FragmentGalleryBinding;
import com.lxq.smartsign.client.util.AttendanceAdapter;
import com.lxq.smartsign.client.util.ClientConfig;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class GalleryFragment extends Fragment {

    private FragmentGalleryBinding binding;
    private SwipeRefreshLayout refreshLayout;
    private RequestQueue queue;
    private RecyclerView recyclerView;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentGalleryBinding.inflate(inflater);
        queue= Volley.newRequestQueue(requireActivity());
        refreshLayout=binding.refreshList;
        recyclerView=binding.attendanceList;
        refreshLayout.setOnRefreshListener(this::refresh);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        refresh();
        return binding.getRoot();
    }

    private void refresh(){
        String url= ClientConfig.SERVER_URL+"/get_attendance";
        JSONObject param=new JSONObject();
        JSONArray array=new JSONArray();
        try {
            param.put("userId",ClientConfig.USER_ID);
            array.put(param);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonArrayRequest request=new JsonArrayRequest(Request.Method.POST,url,array, response -> {
            AttendanceAdapter adapter=new AttendanceAdapter(response);
            recyclerView.setAdapter(adapter);
            refreshLayout.setRefreshing(false);
        },error ->{
            Toast.makeText(getActivity(), "刷新失败", Toast.LENGTH_SHORT).show();
            refreshLayout.setRefreshing(false);
        });
        queue.add(request);
    }
}